package com.minimalist.tc.service;

import com.minimalist.common.config.redis.RedisManager;
import com.minimalist.common.entity.tc.config.BaiduConfig.BaiduApiProperties;
import com.minimalist.common.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 百度API服务类
 *
 * @author 11987
 */
@Service
public class BaiduApiService{
    private static final Logger log = LoggerFactory.getLogger(BaiduApiService.class);


    @Autowired
    private OkHttpClient httpClient;


    @Autowired
    private BaiduApiProperties baiduApiProperties;

    @Autowired
    private RedisManager redisManager;

    /**
     * 百度API访问令牌的Redis缓存键
     */
    private static final String BAIDU_ACCESS_TOKEN_KEY = "baidu:access_token";

    /**
     * 获取百度API访问令牌
     *
     * @return 访问令牌响应
     */
    public String getAccessToken(){
        // 先从Redis缓存中获取token
        String cachedToken = redisManager.get(BAIDU_ACCESS_TOKEN_KEY);
        if (cachedToken != null){
            log.info("从Redis缓存中获取百度API访问令牌");
            return cachedToken;
        }

        // 缓存中没有，则请求百度API获取新token
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");

        String url = String.format("%s?client_id=%s&client_secret=%s&grant_type=client_credentials",
                baiduApiProperties.getTokenUrl(),
                baiduApiProperties.getApiKey(),
                baiduApiProperties.getSecretKey());

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        try (Response response = httpClient.newCall(request).execute()){
            if (response.body() != null){
                String responseBody = response.body().string();
                log.info("获取百度API访问令牌成功");

                // 解析响应，获取token和过期时间
                Map<String, Object> tokenInfo = GsonUtils.fromJson(responseBody, Map.class);
                if (tokenInfo != null && tokenInfo.containsKey("access_token") && tokenInfo.containsKey("expires_in")){
                    String accessToken = (String) tokenInfo.get("access_token");
                    // expires_in是秒为单位的过期时间
                    double expiresIn = Double.parseDouble(tokenInfo.get("expires_in").toString());

                    // 将token存入Redis，设置过期时间比API返回的稍短一些，避免边界问题
                    // 一般设置为原过期时间的90%左右
                    int cacheExpireTime = (int) (expiresIn * 0.9);
                    redisManager.set(BAIDU_ACCESS_TOKEN_KEY, accessToken, cacheExpireTime);
                    log.info("百度API访问令牌已缓存到Redis，过期时间：{} 秒", cacheExpireTime);

                    return accessToken;
                }

                return responseBody;
            }
        } catch (IOException e){
            log.error("获取百度API访问令牌失败", e);
        }
        return null;
    }

    /**
     * 清除缓存的访问令牌
     */
    public void clearAccessTokenCache(){
        redisManager.delete(BAIDU_ACCESS_TOKEN_KEY);
        log.info("已清除百度API访问令牌缓存");
    }
}
